package com.cjh.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TestJwt {

    /**
     * 生成加密的token的方法
     * @param userName
     * @return
     */
    public static String createJwt(String userName){
        //颁发时间
        Date createTime=new Date();
        //过期时间
        Calendar now = Calendar.getInstance();
        //设置未来的时间
        now.set(Calendar.SECOND,7200);
        Date expireTime = now.getTime();
        //header
        Map<String,Object> header=new HashMap<>(4);
        header.put("alg","HS256");
        header.put("typ","JWT");
        //载体
        String token = JWT.create()
                .withHeader(header)
                .withIssuedAt(createTime)
                .withExpiresAt(expireTime)
                .withSubject("这是一个jwt")
                .withClaim("userName", userName)
                .sign(Algorithm.HMAC256("cjh-jwt-sign"));
        return token;
    }

    /**
     * 解密的方法
     * @param token
     * @return
     */
    public static boolean deCodeJwt(String token){
        //先验证签名
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("cjh-jwt-sign")).build();
        try {
            //解密 verify里面可以get很多东西
            DecodedJWT verify = jwtVerifier.verify(token);
            Claim userNameClaim = verify.getClaim("userName");
            String userName = userNameClaim.asString();
            System.out.println(userName);
            return true;
        } catch (JWTVerificationException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void main(String[] args) {
        String token = createJwt("cjh");
        System.out.println(token);
        boolean flag = deCodeJwt(token);
        System.out.println(flag);
    }
}
